package book.dao.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import book.dao.IBookDao;
import book.po.Book;

/**
 * 数据访问对象实现类——文件
 * 文件存储对象
 *
 */
public class BookDaoFileImpl implements IBookDao{
	private static File file; 
	private static List<Book> library = new ArrayList<Book>(); //static确保所有service对象共用图书集合
	static {
		file = new File("library.txt"); 
		List<Book> bookList = new ArrayList<Book>();	
		try {
			FileInputStream fi = new FileInputStream(file);
			ObjectInputStream oi = new ObjectInputStream(fi);
			bookList = (ArrayList<Book>) oi.readObject();
			fi.close();
			oi.close();
		} catch (Exception e) {
		}
		library = bookList;
	}

	@Override
	public void save(Book book) {
		library.add(book);
		writeBooksIntoFile(library);
	}

	@Override
	public void update(int id, Book book) {
		library.set(id, book);
		writeBooksIntoFile(library);
	}

	@Override
	public Book get(int id) {
		return library.get(id);
	}

	@Override
	public void delete(int id) {
		library.remove(id);
		writeBooksIntoFile(library);
	}

	@Override
	public List<Book> findAll() {
		return library;
	}
	/**
	 * 将图书写入文件
	 * 
	 * @param bookList
	 */
	public void writeBooksIntoFile(List<Book> books) {
		try {
			FileOutputStream fo = new FileOutputStream(file);
			ObjectOutputStream out = new ObjectOutputStream(fo);
			out.writeObject(books);
			out.close();
		} catch (Exception e) {
		}
	}

	@Override
	public void update(Book book) {
		// 数据库DAO专用更新接口
	}
}
